<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">餐饮类型</label>
        <el-select v-model="query.type" style="width: 160px" placeholder="请选择餐饮类型">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <label class="el-form-item-label">菜名</label>
        <el-input v-model="query.dishName" clearable placeholder="菜名" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
        <div>
          <el-button type="primary" round @click="openCanteenPrice">价格设置</el-button>
          <el-button type="primary" round @click="openCanteenDiscount">优惠设置</el-button>
          <!--优惠设置表格渲染-->
          <el-dialog
            title="优惠设置"
            :visible.sync="canteenDiscountDialogDetailVisible"
            width="50%"
            :before-close="closeCanteenDiscount"
          >
            <div>
              <el-button type="primary" @click="openCanteenDiscountDialog(true)">新增配置</el-button>
            </div>
            <el-table ref="table" v-loading="loading" :data="canteenDiscountList" size="small" style="width: 100%;">
              <el-table-column type="content" width="55" />
              <el-table-column prop="discountName" label="折扣人群" />
              <el-table-column prop="breakfast" label="早餐折扣" />
              <el-table-column prop="lunch" label="午餐折扣" />
              <el-table-column prop="dinner" label="晚餐折扣" />
              <el-table-column prop="supper" label="其他折扣" />
              <el-table-column label="操作" width="150px" align="center">
                <template slot-scope="scope">
                  <el-button type="primary" @click="openCanteenDiscountDialog(false, scope.row)">编辑</el-button>
                  <el-button type="danger" @click="removeCanteenDiscount(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-dialog>
          <!--价格设置表格渲染-->
          <el-dialog
            title="价格设置"
            :visible.sync="canteenPriceDialogDetailVisible"
            width="30%"
            :before-close="closeCanteenPrice"
          >
            <div>
              <el-button type="primary" @click="openCanteenPriceDialog(true)">新增配置</el-button>
            </div>
            <el-table ref="table" v-loading="loading" :data="canteenPriceList" size="small" style="width: 100%;">
              <el-table-column type="content" width="55" />
              <el-table-column prop="type" label="餐饮类型" >
                <template slot-scope="scope">
                  <!-- 根据不同的值显示不同的内容 -->
                  <span v-if="scope.row.type == 1">早餐</span>
                  <span v-else-if="scope.row.type == 2">午餐</span>
                  <span v-else-if="scope.row.type == 3">晚餐</span>
                  <span v-else-if="scope.row.type == 4">其他</span>
                  <span v-else />
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作" width="150px" align="center">
                <template slot-scope="scope">
                  <el-button type="primary" @click="openCanteenPriceDialog(false, scope.row)">编辑</el-button>
                  <el-button type="danger" @click="removeCanteenPrice(scope.row)">删除</el-button>
                </template>

              </el-table-column>
            </el-table>
          </el-dialog>
          <!--价格设置新增编辑-->
          <el-dialog
            :title="canteenPriceSetTitle"
            :visible.sync="canteenPriceAddEditDialogDetailVisible"
            width="30%"
            :before-close="closeCanteenPriceDialog"
          >
            <el-form ref="form" :model="canteenPriceDetail" :rules="rules" size="small" label-width="80px">
              <el-form-item label="餐饮类型" prop="type">
                <el-select v-model="canteenPriceDetail.type" style="width: 160px" placeholder="请选择餐饮类型">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="价格" prop="price">
                <el-input-number v-model="canteenPriceDetail.price" :precision="2" :step="0.1" :min="0" :max="100"></el-input-number>
              </el-form-item>
              <el-form-item label="描述" prop="price">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="canteenPriceDetail.description">
                </el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="text" @click="closeCanteenPriceDialog">取消</el-button>
              <el-button :loading="loading" type="primary" @click="commitAddPriceDetail">确认</el-button>
            </div>
          </el-dialog>
          <!--价格设置新增编辑-->
          <el-dialog
            :title="canteenDiscountSetTitle"
            :visible.sync="canteenDiscountAddEditDialogDetailVisible"
            width="30%"
            :before-close="closeCanteenDiscountDialog"
          >
            <el-form ref="form" :model="canteenDiscountDetail" :rules="rules" size="small" label-width="80px">
              <el-form-item label="折扣人群">
                <el-input v-model="canteenDiscountDetail.discountName" placeholder="请输入折扣人群"></el-input>
              </el-form-item>
              <el-form-item label="早餐折扣">
                <el-input-number v-model="canteenDiscountDetail.breakfast" :precision="1" :step="0.1" :min="0" :max="10"></el-input-number>
              </el-form-item>
              <el-form-item label="午餐折扣">
                <el-input-number v-model="canteenDiscountDetail.lunch" :precision="1" :step="0.1" :min="0" :max="10"></el-input-number>
              </el-form-item>
              <el-form-item label="晚餐折扣">
                <el-input-number v-model="canteenDiscountDetail.dinner" :precision="1" :step="0.1" :min="0" :max="10"></el-input-number>
              </el-form-item>
              <el-form-item label="其他折扣">
                <el-input-number v-model="canteenDiscountDetail.supper" :precision="1" :step="0.1" :min="0" :max="10"></el-input-number>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="text" @click="closeCanteenDiscountDialog">取消</el-button>
              <el-button :loading="loading" type="primary" @click="commitAddDiscountDetail">确认</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="餐饮类型" prop="type">
            <el-select v-model="form.type" style="width: 160px" placeholder="请选择餐饮类型">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="菜名" prop="dishName">
            <el-input v-model="form.dishName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="图片">
            <!-- 文件上传组件 -->
            <el-upload
              class="upload-demo"
              :limit="1"
              :action="fileUploadApi"
              :headers="headers"
              :on-preview="handlePreview"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :on-remove="removePic"
              :on-error="handleError"
              :file-list="fileList"
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500mb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="dishName" label="菜名" />
        <el-table-column prop="type" label="餐饮类型" >
          <template slot-scope="scope">
            <!-- 根据不同的值显示不同的内容 -->
            <span v-if="scope.row.type == 1">早餐</span>
            <span v-else-if="scope.row.type == 2">午餐</span>
            <span v-else-if="scope.row.type == 3">晚餐</span>
            <span v-else-if="scope.row.type == 4">其他</span>
            <span v-else />
          </template>
        </el-table-column>
        <el-table-column prop="path" label="菜品图片">
          <template slot-scope="{row}">
            <el-image
              :src="row.path"
              :preview-src-list="[row.path]"
              fit="contain"
              lazy
              class="el-avatar"
            >
              <div slot="error">
                <i class="el-icon-document" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="shelves" label="菜单状态" >
          <template slot-scope="scope">
            <!-- 根据不同的值显示不同的内容 -->
            <span v-if="scope.row.shelves === 2" style="color: red">下架</span>
            <span v-else-if="scope.row.shelves === 1" style="color: green">上架</span>
            <span v-else />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建日期" />
        <el-table-column v-if="checkPer(['admin','canteenManage:edit','canteenManage:del'])" label="操作" width="300px" align="center">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-button v-if="scope.row.shelves == 2" size="mini" type="primary" @click="conversionShelves(scope.row, 1)">上架</el-button>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-button v-if="scope.row.shelves === 1" size="mini" type="primary" @click="conversionShelves(scope.row, 2)">下架</el-button>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple-light">
                  <udOperation
                    :data="scope.row"
                    :permission="permission"
                  />
                </div>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <el-dialog :visible.sync="dialogPictrueVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </div>
</template>

<script>
import crudCanteenManage, { edit } from '@/api/system/canteenManage'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

const defaultForm = { id: null, createTime: null, updateTime: null, createBy: null, updateBy: null, deleted: null, xqId: null, type: null, storageId: null, path: null, dishName: null }
export default {
  name: 'CanteenManage',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '食堂数据管理', url: 'api/canteenManage', idField: 'id', sort: 'id,desc', crudMethod: { ...crudCanteenManage }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'canteenManage:add'],
        edit: ['admin', 'canteenManage:edit'],
        del: ['admin', 'canteenManage:del']
      },
      rules: {
        type: [
          { required: true, message: '餐饮类型不能为空', trigger: 'blur' }
        ],
        dishName: [
          { required: true, message: '菜名不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'type', display_name: '餐饮类型 1早餐 2午餐 3晚餐 4其他' },
        { key: 'dishName', display_name: '菜名' }
      ],
      options: [{
        value: '1',
        label: '早餐'
      }, {
        value: '2',
        label: '午餐'
      }, {
        value: '3',
        label: '晚餐'
      }, {
        value: '4',
        label: '其他'
      }],
      headers: { 'Authorization': getToken() },
      fileList: [],
      dialogImageUrl: '',
      dialogPictrueVisible: false,
      canteenPriceDialogDetailVisible: false,
      loading: false,
      canteenPriceList: [],
      canteenPriceAddEditDialogDetailVisible: false,
      canteenPriceSetTitle: '',
      canteenPriceDetail: {
        'id': null,
        'type': null,
        'price': null,
        'description': null
      },
      canteenDiscountDialogDetailVisible: false,
      canteenDiscountList: [],
      canteenDiscountAddEditDialogDetailVisible: false,
      canteenDiscountSetTitle: '',
      canteenDiscountDetail: {
        'id': null,
        'discountName': null,
        'breakfast': 10,
        'lunch': 10,
        'dinner': 10,
        'supper': 10
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.optShow.download = false
      return true
    },
    // 编辑之前
    [CRUD.HOOK.beforeToEdit](obj, row) {
      this.fileList.push({ url: row.path })
      return true
    },
    // 取消添加之前
    [CRUD.HOOK.beforeAddCancel]() {
      this.fileList = []
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      return true
    },
    // 取消编辑之前
    [CRUD.HOOK.beforeEditCancel]() {
      this.fileList = []
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      return true
    },
    // 提交之前
    [CRUD.HOOK.beforeSubmit]() {
      // if (!this.crud.form.path || this.crud.form.path === '') {
      //   this.$message.error('请上传文件')
      //   return false
      // }
      // if (!this.crud.form.storageId || this.crud.form.storageId === '') {
      //   this.$message.error('请上传文件')
      //   return false
      // }
      return true
    },
    // 提交保存之后
    [CRUD.HOOK.afterSubmit]() {
      this.fileList = []
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      return true
    },
    // 上下架
    conversionShelves(row, shelves) {
      row.shelves = shelves
      this.loading = true
      crudCanteenManage.edit(row).then(data => {
        this.loading = false
        this.crud.operationSuccessNotify()
        this.crud.refresh()
      })
    },
    // 删除图片
    removePic() {
      this.crud.form.path = ''
      this.crud.form.storageId = ''
    },
    handleSuccess(res, file, fileList) {
      this.crud.form.path = res.path
      this.crud.form.storageId = res.id
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.dialogVisible = false
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogPictrueVisible = true
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 5mb!')
      }
      return isLt2M
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    // 打开价格设置dialog
    openCanteenPrice() {
      this.canteenPriceDialogDetailVisible = true
      this.laodCanteenPriceList()
    },
    openCanteenDiscount() {
      this.canteenDiscountDialogDetailVisible = true
      this.laodCanteenDiscountList()
    },
    // 加载设置列表
    laodCanteenPriceList() {
      this.loading = true
      crudCanteenManage.getCanteenPriceList().then(data => {
        console.log(data.data)
        if (data && data.data) {
          this.canteenPriceList = data.data.records
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    laodCanteenDiscountList() {
      this.loading = true
      crudCanteenManage.getCanteenDiscountList().then(data => {
        console.log(data.data)
        if (data && data.data) {
          this.canteenDiscountList = data.data.records
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 关闭价格设置dialog
    closeCanteenPrice() {
      this.canteenPriceDialogDetailVisible = false
    },
    closeCanteenDiscount() {
      this.canteenDiscountDialogDetailVisible = false
    },
    // 打开价格设置dialog
    openCanteenPriceDialog(isAdd, row) {
      if (isAdd) {
        this.canteenPriceSetTitle = '新增设置'
      } else {
        if (!row) {
          this.$notify({
            title: '请选择要编辑的数据',
            type: 'error',
            duration: 2500
          })
          return false
        }
        this.canteenPriceSetTitle = '编辑设置'
        this.canteenPriceDetail.id = row.id
        this.canteenPriceDetail.price = row.price
        this.canteenPriceDetail.type = row.type
      }
      this.canteenPriceAddEditDialogDetailVisible = true
    },
    openCanteenDiscountDialog(isAdd, row) {
      if (isAdd) {
        this.canteenDiscountSetTitle = '新增设置'
      } else {
        if (!row) {
          this.$notify({
            title: '请选择要编辑的数据',
            type: 'error',
            duration: 2500
          })
          return false
        }
        this.canteenDiscountSetTitle = '编辑设置'
        this.canteenDiscountDetail.id = row.id
        this.canteenDiscountDetail.discountName = row.discountName
        this.canteenDiscountDetail.breakfast = row.breakfast
        this.canteenDiscountDetail.lunch = row.lunch
        this.canteenDiscountDetail.dinner = row.dinner
        this.canteenDiscountDetail.supper = row.supper
      }
      this.canteenDiscountAddEditDialogDetailVisible = true
    },
    // 关闭价格设置dialog
    closeCanteenPriceDialog() {
      this.canteenPriceAddEditDialogDetailVisible = false
      this.canteenPriceDetail.id = null
      this.canteenPriceDetail.price = null
      this.canteenPriceDetail.type = null
    },
    closeCanteenDiscountDialog() {
      this.canteenDiscountAddEditDialogDetailVisible = false
      this.canteenDiscountDetail.id = null
      this.canteenDiscountDetail.discountName = null
      this.canteenDiscountDetail.breakfast = 10
      this.canteenDiscountDetail.lunch = 10
      this.canteenDiscountDetail.dinner = 10
      this.canteenDiscountDetail.supper = 10
    },
    removeCanteenPrice(row) {
      if (!row) {
        this.$notify({
          title: '请选择要编辑的数据',
          type: 'error',
          duration: 2500
        })
        return false
      }
      crudCanteenManage.deletePrice([row.id]).then(data => {
        if (data && data.code === 200) {
          this.$notify({
            title: data.data,
            type: 'success',
            duration: 2500
          })
        }
        this.laodCanteenPriceList()
      })
    },
    removeCanteenDiscount(row) {
      if (!row) {
        this.$notify({
          title: '请选择要编辑的数据',
          type: 'error',
          duration: 2500
        })
        return false
      }
      crudCanteenManage.deleteDiscount([row.id]).then(data => {
        if (data && data.code === 200) {
          this.$notify({
            title: data.data,
            type: 'success',
            duration: 2500
          })
        }
        this.laodCanteenDiscountList()
      })
    },
    commitAddPriceDetail() {
      if (!this.canteenPriceDetail.type) {
        this.$notify({
          title: '请选择餐饮类型',
          type: 'error',
          duration: 2500
        })
        return false
      }
      if (!this.canteenPriceDetail.price || this.canteenPriceDetail.price === 0) {
        this.$notify({
          title: '请填写价格',
          type: 'error',
          duration: 2500
        })
        return false
      }
      crudCanteenManage.priceSaveOrUpdate(this.canteenPriceDetail).then(data => {
        if (data && data.code === 200) {
          this.$notify({
            title: data.data,
            type: 'success',
            duration: 2500
          })
        }
        this.closeCanteenPriceDialog()
        this.laodCanteenPriceList()
      })
    },
    commitAddDiscountDetail() {
      if (!this.canteenDiscountDetail.discountName || this.canteenDiscountDetail.discountName === '') {
        this.$notify({
          title: '请填写折扣人群',
          type: 'error',
          duration: 2500
        })
        return false
      }
      crudCanteenManage.discountSaveOrUpdate(this.canteenDiscountDetail).then(data => {
        if (data && data.code === 200) {
          this.$notify({
            title: data.data,
            type: 'success',
            duration: 2500
          })
        }
        this.closeCanteenDiscountDialog()
        this.laodCanteenDiscountList()
      })
    }
  }
}
</script>

<style scoped>

</style>
